/*
** my_showmem.c for my_showmem in /home/goupil_r//afs/Jour_06/ex_18
** 
** Made by robin goupil
** Login   <goupil_r@epitech.net>
** 
** Started on  Tue Oct  9 18:38:57 2012 robin goupil
** Last update Sat Nov 17 10:26:20 2012 robin goupil
*/

void    my_get_rest_long_base(long u_nb, long size, char *base)
{
  int   i;
  char  result[32];
  int   base_length;

  i = 0;
  base_length = 0;
  while (base[base_length] != '\0')
    {
      base_length = base_length + 1;
    }
  while (u_nb / base_length > 0)
    {
      result[i] = base[u_nb % base_length];
      u_nb = (u_nb - (u_nb % base_length)) / base_length;
      i = i + 1;
    }
  result[i] = base[u_nb % base_length];
  while (i >= 0)
    {
      my_putchar(result[i]);
      i = i - 1;
    }
}

int    my_putnbr_long_base(long nbr, char *base)
{
  long  size;
  long  sign;

  size = 1;
  sign = 1;
  while (nbr / (size * 10) != 0)
    {
      size = size * 10;
    }
  if (nbr < 0)
    {
      my_putchar('-');
      sign = (-1);
    }
  my_get_rest_long_base(nbr * sign, size, base);
  return (nbr);
}

void	aff_addr(long addr)
{
  long	size;
  long	addr_bis;

  size = 1;
  addr_bis = addr;
  while (addr_bis > 0)
    {
      size = size + 1;
      addr_bis = addr_bis / 10;
    }
  while (size % 16 != 0)
    {
      my_putchar('0');
      size = size + 1;
    }
  my_putnbr_long_base(addr, "0123456789ABCDEF");
  my_putchar(':');
  my_putchar(' ');
}

void	aff_hex_values(char *str, int ligne)
{
  long	val;
  int	i;
  int	size;

  i = 0;
  while (i < 16)
    {
      size = 1;
      val = str[ligne + i];
      if (val < 0)
	val = val * (-1);
      if (val < 16)
	my_putchar('0');
      my_putnbr_long_base(val, "0123456789abcdef");
      if (i % 2 != 0)
	my_putchar(' ');
      i = i + 1;
    }
}

int	my_showmem(char *str, int size)
{
  int	ligne;
  int	i;
  int	j;

  ligne = 0;
  while (ligne / 16 < size)
    {
      aff_addr((long)&str[ligne]);
      aff_hex_values(&str[ligne], ligne);
      j = 0;
      while (j < 16)
	{
	  if (str[ligne + j] < 32 || str[ligne + j] > 126)
	    my_putchar('.');
	  else
	    my_putchar(str[ligne + j]);
	  j = j + 1;
	}
      ligne = ligne + 16;
      my_putchar('\n');
    }
}
